﻿@{
    Layout = null;
    ViewData["Title"] = "生产工单甘特图";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>生产工单甘特图</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <script src="~/layui/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .gantt-container {
            margin: 10px;
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 1px 6px rgba(0,0,0,0.1);
        }

        .gantt-header {
            padding: 10px;
            border-bottom: 1px solid #e6e6e6;
            background: #f8f9fa;
            border-radius: 6px 6px 0 0;
        }

        .gantt-toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .gantt-search {
            display: flex;
            gap: 5px;
            align-items: center;
        }

        .gantt-chart {
            position: relative;
            overflow: auto;
            height: 500px;
        }

        .gantt-table {
            display: flex;
            min-width: 100%;
        }

        .gantt-left {
            flex: 0 0 430px;
            border-right: 1px solid #e6e6e6;
            background: #fafafa;
        }

        .gantt-right {
            flex: 1;
            position: relative;
            background: #fff;
        }

        .gantt-left-header {
            height: 35px;
            display: flex;
            background: #f0f0f0;
            border-bottom: 1px solid #e6e6e6;
            font-weight: bold;
        }

            .gantt-left-header > div {
                display: flex;
                align-items: center;
                justify-content: center;
                border-right: 1px solid #e6e6e6;
                padding: 4px;
                font-size: 12px;
            }

        .gantt-row {
            height: 30px;
            display: flex;
            border-bottom: 1px solid #e6e6e6;
            position: relative;
        }

            .gantt-row:nth-child(even) {
                background: #f9f9f9;
            }

            .gantt-row:hover {
                background: #e8f4fd;
            }

            .gantt-row > div {
                display: flex;
                align-items: center;
                padding: 4px;
                border-right: 1px solid #e6e6e6;
                font-size: 11px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

        .gantt-timeline {
            height: 35px;
            display: flex;
            background: #f0f0f0;
            border-bottom: 1px solid #e6e6e6;
            position: relative;
        }

        .gantt-timeline-date {
            flex: 1;
            min-width: 60px;
            border-right: 1px solid #e6e6e6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            font-weight: bold;
        }

        .gantt-timeline-grid {
            position: absolute;
            top: 0;
            bottom: 0;
            border-left: 1px solid #e6e6e6;
            opacity: 0.3;
        }

        .gantt-bar {
            position: absolute;
            height: 16px;
            top: 7px;
            border-radius: 3px;
            color: white;
            font-size: 10px;
            display: flex;
            align-items: center;
            padding: 0 6px;
            white-space: nowrap;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0,0,0,0.2);
        }

            .gantt-bar:hover {
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0,0,0,0.3);
            }

        .gantt-bar-progress {
            background: linear-gradient(90deg, #4CAF50, #45a049);
            border: 1px solid #3d8b40;
        }

        .gantt-bar-planned {
            background: linear-gradient(90deg, #2196F3, #1976D2);
            border: 1px solid #1565C0;
        }

        .gantt-bar-delayed {
            background: linear-gradient(90deg, #FF9800, #F57C00);
            border: 1px solid #E65100;
        }

        .gantt-bar-completed {
            background: linear-gradient(90deg, #4CAF50, #2E7D32);
            border: 1px solid #1B5E20;
        }

        .gantt-today-line {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #f44336;
            z-index: 10;
        }

        .status-draft {
            color: #999;
        }

        .status-progress {
            color: #1890ff;
        }

        .status-completed {
            color: #52c41a;
        }

        .status-paused {
            color: #fa8c16;
        }
        
        /* 更紧凑的表单元素 */
        .layui-input, .layui-select, .layui-textarea {
            height: 30px;
            line-height: 30px;
        }
        
        .layui-btn {
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
        }
        
        .layui-form-item {
            margin-bottom: 5px;
        }
        
        h2 {
            font-size: 16px;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div class="gantt-container">
        <div class="gantt-header">
            <div class="gantt-toolbar">
                <div>
                    <h2><i class="layui-icon layui-icon-chart"></i> 生产工单甘特图</h2>
                </div>
                <div class="gantt-search">
                    <div class="layui-form layui-form-pane" style="display: flex; gap: 5px; margin: 0;">
                        <div class="layui-form-item" style="margin: 0;">
                            <div class="layui-input-inline" style="width: 120px;">
                                <input type="text" id="searchOrderName" placeholder="请输入工单名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <div class="layui-input-inline" style="width: 100px;">
                                <input type="text" id="startDate" placeholder="开始日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <div class="layui-input-inline" style="width: 100px;">
                                <input type="text" id="endDate" placeholder="结束日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <button class="layui-btn layui-btn-primary" id="btnSearch">
                                <i class="layui-icon layui-icon-search"></i> 搜索
                            </button>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <button class="layui-btn" id="btnRefresh">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <button class="layui-btn layui-btn-normal" id="btnZoomOut">
                                <i class="layui-icon layui-icon-subtraction"></i> 缩小
                            </button>
                        </div>
                        <div class="layui-form-item" style="margin: 0;">
                            <button class="layui-btn layui-btn-normal" id="btnZoomIn">
                                <i class="layui-icon layui-icon-addition"></i> 放大
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div style="display: flex; gap: 10px; font-size: 11px; color: #666;">
                <div><span style="background: #4CAF50; width: 10px; height: 10px; display: inline-block; margin-right: 3px;"></span>进行中</div>
                <div><span style="background: #2196F3; width: 10px; height: 10px; display: inline-block; margin-right: 3px;"></span>计划中</div>
                <div><span style="background: #FF9800; width: 10px; height: 10px; display: inline-block; margin-right: 3px;"></span>延期</div>
                <div><span style="background: #4CAF50; width: 10px; height: 10px; display: inline-block; margin-right: 3px;"></span>已完成</div>
            </div>
        </div>

        <div class="gantt-chart">
            <div class="gantt-table">
                <div class="gantt-left">
                    <div class="gantt-left-header">
                        <div style="width: 70px;">工单编码</div>
                        <div style="width: 100px;">工单名称</div>
                        <div style="width: 70px;">来源单据</div>
                        <div style="width: 70px;">产品编号</div>
                        <div style="width: 70px;">产品名称</div>
                        <div style="width: 50px;">客户编码</div>
                    </div>
                    <div id="ganttLeftContent">
                        <!-- 工单数据行将在这里动态生成 -->
                    </div>
                </div>
                <div class="gantt-right">
                    <div class="gantt-timeline" id="ganttTimeline">
                        <!-- 时间轴将在这里动态生成 -->
                    </div>
                    <div id="ganttRightContent">
                        <!-- 甘特图条将在这里动态生成 -->
                    </div>
                    <div class="gantt-today-line" id="todayLine"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        layui.use(['layer', 'form', 'laydate'], function() {
            var layer = layui.layer;
            var form = layui.form;
            var laydate = layui.laydate;

            // 全局变量
            var ganttData = [];
            var dateRange = {
                startDate: null,
                endDate: null,
                dayWidth: 60
            };

            // 初始化
            init();

            function init() {
                initDatePickers();
                loadProductionData();
                bindEvents();
            }

            // 初始化日期选择器
            function initDatePickers() {
                laydate.render({
                    elem: '#startDate',
                    type: 'date',
                    format: 'yyyy-MM-dd'
                });

                laydate.render({
                    elem: '#endDate',
                    type: 'date',
                    format: 'yyyy-MM-dd'
                });
            }

            // 绑定事件
            function bindEvents() {
                $('#btnSearch').on('click', function() {
                    var orderName = $('#searchOrderName').val();
                    var startDate = $('#startDate').val();
                    var endDate = $('#endDate').val();
                    loadProductionData(orderName, startDate, endDate);
                });

                $('#btnRefresh').on('click', function() {
                    $('#searchOrderName').val('');
                    $('#startDate').val('');
                    $('#endDate').val('');
                    loadProductionData();
                });

                $('#btnZoomIn').on('click', function() {
                    if (dateRange.dayWidth < 150) {
                        dateRange.dayWidth += 20;
                        renderGanttChart();
                    }
                });

                $('#btnZoomOut').on('click', function() {
                    if (dateRange.dayWidth > 40) {
                        dateRange.dayWidth -= 20;
                        renderGanttChart();
                    }
                });

                $('#searchOrderName').on('keypress', function(e) {
                    if (e.which === 13) {
                        $('#btnSearch').click();
                    }
                });

                // 添加甘特图条点击事件
                $(document).on('click', '.gantt-bar', function() {
                    var index = $(this).closest('.gantt-row').index();
                    if (ganttData[index]) {
                        showOrderDetail(ganttData[index]);
                    }
                });
            }

            // 加载生产工单数据
            function loadProductionData(orderName = '', startDate = '', endDate = '') {
                layer.load(1);
                
                // 使用新的API路由
                $.ajax({
                    url: '/api/ProductionWorkOrder/GetGanttData',
                    type: 'GET',
                    data: {
                        pageIndex: 1,
                        pageSize: 100,
                        orderName: orderName
                    },
                    success: function(res) {
                        layer.closeAll('loading');
                        if (res.code === 0) {
                            ganttData = res.data || [];
                            // 如果指定了日期范围，进行筛选
                            if (startDate && endDate) {
                                ganttData = ganttData.filter(function(item) {
                                    if (item.demandDate) {
                                        var demandDate = new Date(item.demandDate);
                                        var filterStartDate = new Date(startDate);
                                        var filterEndDate = new Date(endDate);
                                        return demandDate >= filterStartDate && demandDate <= filterEndDate;
                                    }
                                    return true;
                                });
                            }
                            processGanttData();
                            renderGanttChart();
                        } else {
                            layer.msg('获取数据失败：' + res.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.closeAll('loading');
                        console.error('API请求错误:', xhr.status, xhr.responseText);
                        layer.msg('数据加载失败，请检查网络连接');
                    }
                });
            }

            // 处理甘特图数据
            function processGanttData() {
                if (ganttData.length === 0) return;

                var dates = [];
                var today = new Date();

                ganttData.forEach(function(item) {
                    // 处理需求日期
                    if (item.demandDate) {
                        var demandDate = new Date(item.demandDate);
                        dates.push(demandDate);
                    }
                });

                // 如果没有日期数据，使用当前日期前后30天
                if (dates.length === 0) {
                    var start = new Date(today);
                    start.setDate(start.getDate() - 15);
                    var end = new Date(today);
                    end.setDate(end.getDate() + 15);
                    dates = [start, end];
                }

                // 计算日期范围
                var minDate = new Date(Math.min.apply(null, dates));
                var maxDate = new Date(Math.max.apply(null, dates));

                // 扩展日期范围
                minDate.setDate(minDate.getDate() - 7);
                maxDate.setDate(maxDate.getDate() + 7);

                dateRange.startDate = minDate;
                dateRange.endDate = maxDate;

                // 为每个工单添加甘特图属性
                ganttData.forEach(function(item, index) {
                    item.ganttIndex = index;

                    // 计算开始和结束日期
                    var demandDate = item.demandDate ? new Date(item.demandDate) : new Date();
                    var startDate = new Date(demandDate);
                    startDate.setDate(startDate.getDate() - 5); // 假设工单需要5天完成

                    item.startDate = startDate;
                    item.endDate = demandDate;
                    item.progress = getRandomProgress(); // 模拟进度
                    item.status = getStatusByProgress(item.progress);
                });
            }

            // 获取随机进度（实际中应该从数据库获取）
            function getRandomProgress() {
                return Math.floor(Math.random() * 100);
            }

            // 根据进度获取状态
            function getStatusByProgress(progress) {
                if (progress === 0) return 'planned';
                if (progress < 100) return 'progress';
                return 'completed';
            }

            // 渲染甘特图
            function renderGanttChart() {
                renderTimeline();
                renderLeftContent();
                renderRightContent();
                renderTodayLine();
            }

            // 渲染时间轴
            function renderTimeline() {
                var timeline = $('#ganttTimeline');
                timeline.empty();

                var currentDate = new Date(dateRange.startDate);
                var endDate = new Date(dateRange.endDate);

                while (currentDate <= endDate) {
                    var dateStr = formatDate(currentDate);
                    var dayOfWeek = currentDate.getDay();
                    var isWeekend = dayOfWeek === 0 || dayOfWeek === 6;

                    var dateDiv = $('<div class="gantt-timeline-date"></div>')
                        .css({
                            'width': dateRange.dayWidth + 'px',
                            'background-color': isWeekend ? '#f0f0f0' : '#fff',
                            'color': isWeekend ? '#999' : '#333'
                        })
                        .text(dateStr);

                    timeline.append(dateDiv);
                    currentDate.setDate(currentDate.getDate() + 1);
                }
            }

            // 渲染左侧内容
            function renderLeftContent() {
                var leftContent = $('#ganttLeftContent');
                leftContent.empty();

                if (ganttData.length === 0) {
                    var emptyRow = $('<div style="text-align: center; padding: 50px; color: #999;">暂无工单数据</div>');
                    leftContent.append(emptyRow);
                    return;
                }

                ganttData.forEach(function(item) {
                    var row = $('<div class="gantt-row"></div>');

                    var orderCodeDiv = $('<div></div>').css('width', '80px').text(item.orderCode || '');
                    var orderNameDiv = $('<div></div>').css('width', '120px').text(item.orderName || '');
                    var sourceTypeDiv = $('<div></div>').css('width', '80px').text(item.sourceType || '');
                    var productCodeDiv = $('<div></div>').css('width', '80px').text(item.productionCode || '');
                    var productNameDiv = $('<div></div>').css('width', '80px').text(item.productionName || '');
                    var customerCodeDiv = $('<div></div>').css('width', '60px').text(item.customerCode || '');

                    row.append(orderCodeDiv, orderNameDiv, sourceTypeDiv, productCodeDiv, productNameDiv, customerCodeDiv);
                    leftContent.append(row);
                });
            }

            // 渲染右侧甘特图条
            function renderRightContent() {
                var rightContent = $('#ganttRightContent');
                rightContent.empty();

                ganttData.forEach(function(item, index) {
                    var row = $('<div class="gantt-row"></div>');

                    if (item.startDate && item.endDate) {
                        var startPos = getDatePosition(item.startDate);
                        var endPos = getDatePosition(item.endDate);
                        var width = endPos - startPos;

                        if (width > 0) {
                            var progressWidth = width * (item.progress / 100);

                            // 创建甘特图条
                            var ganttBar = $('<div class="gantt-bar"></div>')
                                .css({
                                    'left': startPos + 'px',
                                    'width': width + 'px'
                                })
                                .addClass('gantt-bar-' + item.status)
                                .text(item.orderName + ' (' + item.progress + '%)');

                            // 如果有进度，显示进度条
                            if (item.progress > 0 && item.progress < 100) {
                                var progressBar = $('<div></div>')
                                    .css({
                                        'position': 'absolute',
                                        'left': '0',
                                        'top': '0',
                                        'bottom': '0',
                                        'width': (item.progress) + '%',
                                        'background': 'rgba(255,255,255,0.3)',
                                        'border-radius': '3px'
                                    });
                                ganttBar.append(progressBar);
                            }

                            row.append(ganttBar);
                        }
                    }

                    rightContent.append(row);
                });
            }

            // 渲染今日线
            function renderTodayLine() {
                var todayPos = getDatePosition(new Date());
                var todayLine = $('#todayLine');
                todayLine.css('left', todayPos + 'px');
            }

            // 获取日期在甘特图中的位置
            function getDatePosition(date) {
                var diffTime = date.getTime() - dateRange.startDate.getTime();
                var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                return diffDays * dateRange.dayWidth;
            }

            // 格式化日期
            function formatDate(date) {
                var month = date.getMonth() + 1;
                var day = date.getDate();
                return month + '/' + day;
            }

            // 显示工单详情
            function showOrderDetail(order) {
                var content = '<div style="padding: 20px; font-size: 14px;">' +
                    '<div style="margin-bottom: 15px;"><strong>工单编码：</strong>' + (order.orderCode || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>工单名称：</strong>' + (order.orderName || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>来源类型：</strong>' + (order.sourceType || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>产品编号：</strong>' + (order.productionCode || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>产品名称：</strong>' + (order.productionName || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>规格型号：</strong>' + (order.specifications || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>工单数量：</strong>' + (order.orderCount || 0) + ' ' + (order.unit || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>需求日期：</strong>' + (order.demandDate ? new Date(order.demandDate).toLocaleDateString() : '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>客户编码：</strong>' + (order.customerCode || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>客户名称：</strong>' + (order.customerName || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>单据状态：</strong>' + (order.documentStatus || '') + '</div>' +
                    '<div style="margin-bottom: 15px;"><strong>完成进度：</strong>' + (order.progress || 0) + '%</div>' +
                    '</div>';

                layer.open({
                    type: 1,
                    title: '工单详情',
                    area: ['600px', '500px'],
                    content: content,
                    btn: ['关闭'],
                    btn1: function(index) {
                        layer.close(index);
                    }
                });
            }
        });
    </script>
</body>
</html>
